//全局变量
var siteList = new Array();
var itemList = new Array();

$(document).ready(
	function(){ 
		$('#consoleDlg')[0].style.display = "none";
		
		//初始化站点select，只加入与用户相绑定的site
		var siteSelect = $("#gridContent").find("#sites");
		siteSelect.empty();		
		$.ajax({
			type: "POST",
			url : getContextPath()+"/user/getUserSites.do",
			data : {},
			dataType : "json",
			async : false,
			cache: false,
			error : function(textStatus, errorThrown) {
				alert("系统ajax交互错误: " + textStatus);
			},
			success : function(data, textStatus) {
				if (data != null) {
					siteList = data;
					for (var i=0; i<data.length; i++) {
						//ie8不支持
						//siteSelect.append(new Option(data[i].id+":"+data[i].name, data[i].id));
						siteSelect.append('<option value="'+data[i].id+'">'+data[i].id+":"+data[i].name+'</option>');
					}
				}
			}
		});
		
		//设置siteSelect的change事件
		siteSelect.change(function() {
			activateGridShow();
		});
		
		
		// 配置对话框
		$("#consoleDlg").dialog( {
			autoOpen : false,
			modal : true, // 设置对话框为模态（modal）对话框
			resizable : true,
			width : 800,
			buttons : { // 为对话框添加按钮
				"取消" : function() {
					$("#consoleDlg").dialog("close")
				},
				"添加" : addInfo,
				"保存" : updateInfo,
				"删除" : deleteInfo
			}
		});  
		
		//初始化对话框中的alarm下拉框
		$.ajax({
			type: "POST",
			url : getContextPath()+"/base/alarmConfig/getAllAlarmConfigsObj.do", 
			data : {},
			dataType : "json",
			async : false,
			cache: false,
			error : function(textStatus, errorThrown) {
				alert("系统ajax交互错误: " + textStatus);
			},
			success : function(data, textStatus) {
				if (data != null) {
					var alarmSelect = $("#consoleDlg").find("#alarm");
					for (var i=0; i<data.length; i++) {
						//ie8不支持
						//alarmSelect.append(new Option(data[i].alarmID+":"+data[i].alarmName, data[i].id));
						alarmSelect.append('<option value="'+data[i].id+'">'+data[i].alarmID+":"+data[i].alarmName+'</option>');
					}
				}
			}
		});
		
		siteSelect.change();
	}
);

function activateGridShow() {
	//根据siteSelect的当前选中的site设置grid
	var curSiteID = $("#gridContent").find("#sites").val();
	var curSite = null;
	for (var j=0; j<siteList.length; j++) {
		if (siteList[j].id == curSiteID) {
			curSite = siteList[j];
			break;
		}
	}
	
	$("#gridTable").setGridParam({datatype:'json', page:1}).setGridParam({postData : {siteID : curSiteID}}).trigger("reloadGrid");
	$("#gridTable").jqGrid({ 
		type: "POST",
        url:getContextPath()+"/site/item/getItemBySite.do", 
        postData : {siteID : curSiteID},
        async : false,
        datatype: "json",// "local",
        height: 350,   
        colNames:['序号' , '项目代码','项目名称', '有效上限值', '有效下限值', '超标上限值' , '超标下限值', '测量标准单位' , '最大量程' , '最小量程' , '转换因子' , '报警级别'],
		colModel:[
		    {name:'id', index:'id', width:70, align:"left", hidden: true},      
			{name:'item.id', index:'item.id', width:70, align:"left"},
			{name:'item.name', index:'item.name', width:100, align:"left"},
	   		{name:'eMaxValue', index:'eMaxValue', width:90, align:"left", sortable:false},
	   		{name:'eMinValue', index:'eMinValue', width:90, align:"left", sortable:false},
	   		{name:'overMaxValue', index:'overMaxValue', width:90, align:"left", sortable:false},
	   		{name:'overMinValue', index:'overMinValue', width:90, align:"left", sortable:false},
	   		{name:'standUnit', index:'standUnit', width:80, align:"left", sortable:false},
	   		{name:'maxRange', index:'maxRange', width:90, align:"left", sortable:false},
	   		{name:'minRange', index:'minRange', width:90, align:"left", sortable:false},
	   		{name:'factor', index:'factor', width:50, align:"left", sortable:false},
	   		{name:'alarm.alarmName', index:'alarm.alarmName', width:50, align:"left", sortable:false}
		],
        sortname:'item.id',   
        // sortorder:'asc',
        viewrecords:true, 
        pgtext : "页 {0} 共 {1}页",
        recordtext:'记录 {0} - {1} 总记录数 {2}',  
        emptyrecords : "无数据",
        loadtext : "获取数据中...",
        rowNum: 15,//10,   
        loadonce: true,
        //rowList:[10,20,30],   
        jsonReader: { 
			repeatitems:false,   	 // 设置成false，在后台设置值的时候，可以乱序。且并非每个值都得设
			root: "rows",               // 数据行（默认为：rows）   
			total: "total",        // 总记录数   
			page: "page",            // 当前页   
			records: "records"   
        }, 
        pager:"#gridPager",  
        caption: "站点监测项目 "
	});
	
	$("#gridTable").jqGrid('navGrid','#gridPager',{edit:false,add:false,del:false});
	
	//根据site的监测类别设置与consoleDlg中与site相关的内容
	var consoleDlg = $("#consoleDlg");
	//consoleDlg.find("#siteID").val(curSite.id);
	consoleDlg.find("#siteID").empty().append(curSite.id);
	consoleDlg.find("#siteName").empty().append(curSite.name);
	consoleDlg.find("#MTypeName").empty().append(curSite.monitorType.name);
	
	//根据site的监测类别设置itemSelect的内容
	var itemSelect = $("#consoleDlg").find("#item");
	itemSelect.empty();
	//ie8不支持
	//itemSelect.append(new Option("--请选择--","no"));
	itemSelect.append('<option value="'+"no"+'">'+"--请选择--"+'</option>');
	$.ajax({
		type: "POST",
		url : getContextPath()+"/base/item/getItemsByMonitorTypeID.do", 
		data : {"mTypeID" : curSite.monitorType.id},
		dataType : "json",
		async : false,
		cache: false,
		error : function(textStatus, errorThrown) {
			alert("系统ajax交互错误: " + textStatus);
		},
		success : function(data, textStatus) {
			if (data != null) {
				itemList = data;
				for (var i=0; i<data.length; i++) {
					//ie8不支持
					//itemSelect.append(new Option(data[i].id+":"+data[i].name, data[i].id));
					itemSelect.append('<option value="'+data[i].id+'">'+data[i].id+":"+data[i].name+'</option>');
				}
			}
		}
	});
	
	itemSelect.selectseach();
	
	//设置itemSelect的change事件
	itemSelect.change(function() {
		var curItemID = itemSelect.val();
		var curItem = null;
		
		if (curItemID == "no") {
			consoleDlg.find("#itemAbrName").empty();
			consoleDlg.find("#itemNationalName").empty();
			consoleDlg.find("#eMaxValue").val("");
			consoleDlg.find("#eMinValue").val("");					
			consoleDlg.find("#overMaxValue").val("");
			consoleDlg.find("#overMinValue").val("");
			consoleDlg.find("#standUnit").val("");
			consoleDlg.find("#scale").val("");
			consoleDlg.find("#maxRange").val("");
			consoleDlg.find("#minRange").val("");
		}
		else {
			for (var j=0; j<itemList.length; j++) {
				if (itemList[j].id == curItemID) {
					curItem = itemList[j];
					break;
				}
			}	
			consoleDlg.find("#itemAbrName").empty().append(curItem.abrName);
			consoleDlg.find("#itemNationalName").empty().append(curItem.nationalName);
			consoleDlg.find("#eMaxValue").val(curItem.eMaxValue);
			consoleDlg.find("#eMinValue").val(curItem.eMinValue);					
			consoleDlg.find("#overMaxValue").val(curItem.overMaxValue);
			consoleDlg.find("#overMinValue").val(curItem.overMinValue);
			consoleDlg.find("#standUnit").val(curItem.standUnit);
			consoleDlg.find("#scale").val(curItem.scale);
			consoleDlg.find("#maxRange").val(curItem.maxRange);
			consoleDlg.find("#minRange").val(curItem.minRange);
		}	
	});
};
		// getContextPath
		function getContextPath() {
    		var pathName = document.location.pathname;
    		var index = pathName.substr(1).indexOf("/");
    		var result = pathName.substr(0,index+1);
    		return result;
		};

		var openDialog4Adding = function() {  
			var consoleDlg = $("#consoleDlg");  
			var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");  
			consoleDlg.find("input").removeAttr("disabled").val(""); 
			consoleDlg.find("select").removeAttr("disabled").val("no");
			dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
			dialogButtonPanel.find("button:contains('添加')").show();  
			consoleDlg.dialog("option", "title", "添加站点监测项目 ").dialog("open");  
		};  
		
		var openDialog4AddingAll = function() {  
			//批量添加所有的item，但已有的item不加入
			var r=confirm("是否要批量导入监测项目（已存在的项目不被导入）？");
			if (r==false) {
				return false;
			}
			//当前站点
			var siteID = $.trim($("#gridContent").find("#sites").val());
			//调用后台服务，批量添加item
			$.ajax({
				type: "POST",
				url : getContextPath()+"/site/item/addAllSiteItem.do", 
				data : {siteID : siteID},
				dataType : "json",
				async : false,
				cache: false,
				error : function(textStatus, errorThrown) {
					alert("系统ajax交互错误: " + textStatus);
				},
				success : function(data, textStatus) {
					if (data != null) {
						//提示已经添加了多少了
						if (data>0) {
							alert("已成功导入"+data+"条监测项目数据");
							$("#gridTable").setGridParam({datatype:'json', page:1}).setGridParam({postData : {siteID : siteID}}).trigger("reloadGrid");
						}
						else {
							alert("没有监测项目被导入");
						}
					}
				}
			});
		};  
		
		var openDialog4Updating = function() {
			var consoleDlg = $("#consoleDlg");  
	        var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");    
	        consoleDlg.find("input").removeAttr("disabled"); 
	        consoleDlg.find("select").removeAttr("disabled");
	        consoleDlg.find("#id").attr("disabled", true);
	        dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
	        dialogButtonPanel.find("button:contains('保存')").show();  
	        consoleDlg.dialog("option", "title", "修改站点监测项目");  
	          
	        loadSelectedRowData();  
		};
		
		var openDialog4Deleting = function() {
			var consoleDlg = $("#consoleDlg");  
	        var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");         
	        consoleDlg.find("input").attr("disabled", true); 
	        consoleDlg.find("select").attr("disabled", true); 
	        dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
	        dialogButtonPanel.find("button:contains('删除')").show();  
	        consoleDlg.dialog("option", "title", "删除站点监测项目");  
	          
	        loadSelectedRowData();  
		};
		
		var loadSelectedRowData = function() {
			var selectedRowId = $("#gridTable").jqGrid("getGridParam", "selrow");
	    	//alert("selectRowID:"+selectedRowId);
	    	if (!selectedRowId) {
	    		alert("请先选择需要编辑的行!");
	    		return false;
	    	} else {
	    		var params = {"id" : selectedRowId};
	    		// 从Server读取对应ID的JSON数据
	    		$.ajax( {
	    			type:"POST",   
	    			url : getContextPath()+"/site/item/getSiteItemByID.do",
	    			data : params,
	    			dataType : "json",
	    			//contentType: "application/json",
	    			cache : false,
	    			async:false,
	    			error : function(textStatus, errorThrown) {
						alert("系统ajax交互错误: " + textStatus.responseText);
					},
					success : function(data, textStatus) {
						// 如果读取结果成功，则将信息载入到对话框中     
						var rowData = data;
						var consoleDlg = $("#consoleDlg");

						consoleDlg.find("#selectId").val(rowData.id);
						consoleDlg.find("#item").val(rowData.item.id);					
						consoleDlg.find("#eMaxValue").val(rowData.eMaxValue);
						consoleDlg.find("#eMinValue").val(rowData.eMinValue);					
						consoleDlg.find("#overMaxValue").val(rowData.overMaxValue);
						consoleDlg.find("#overMinValue").val(rowData.overMinValue);
						consoleDlg.find("#standUnit").val(rowData.standUnit);
						consoleDlg.find("#scale").val(rowData.scale);
						consoleDlg.find("#maxRange").val(rowData.maxRange);
						consoleDlg.find("#minRange").val(rowData.minRange);
						consoleDlg.find("#factor").val(rowData.factor);
						consoleDlg.find("#alarm").val(rowData.alarm.id);
						consoleDlg.find("#remark").val(rowData.remark);
						
						// 根据新载入的数据将表格中的对应数据行一并更新一下
						var dataRow = {
								id : rowData.id,
								"item.id" : rowData.item.id,
								"item.name" : rowData.item.name,
								eMaxValue : rowData.eMaxValue,
								eMinValue : rowData.eMinValue,
								overMaxValue : rowData.overMaxValue,
								overMinValue : rowData.overMinValue,
								standUnit : rowData.standUnit,
								maxRange : rowData.maxRange,
								minRange : rowData.minRange,
						   		factor : rowData.factor,
						   		"alarm.alarmName" : rowData.alarm.alarmName						
						};

						$("#gridTable").jqGrid("setRowData", data.id, dataRow);

						// 打开对话框
						consoleDlg.dialog("open");
					}
	    		});
	    	}
		};
		
		var checkValid = function() {
	    	var consoleDlg = $("#consoleDlg");
	    	
	    	var item = $.trim(consoleDlg.find("#item").val());
	    	if (item=="no") {
	    		alert("'监测项目代码'为必填信息");
	    		return false;
	    	}  	
	    	var item = $.trim(consoleDlg.find("#alarm").val());
	    	if (item=="no") {
	    		alert("'报警级别'为必填信息");
	    		return false;
	    	}  	
	    }
		
		var addInfo = function() {
			var consoleDlg = $("#consoleDlg");

			if (checkValid()==false) return false;
						
			var siteID = $.trim($("#gridContent").find("#sites").val());
			var itemID = $.trim(consoleDlg.find("#item").val());
			var eMaxValue = $.trim(consoleDlg.find("#eMaxValue").val());
			if (eMaxValue=="") eMaxValue = "0";
			var eMinValue = $.trim(consoleDlg.find("#eMinValue").val());			
			if (eMinValue=="") eMinValue = "0";
			var overMaxValue = $.trim(consoleDlg.find("#overMaxValue").val());
			if (overMaxValue=="") overMaxValue = "0";
			var overMinValue = $.trim(consoleDlg.find("#overMinValue").val());
			if (overMinValue=="") overMinValue="0";			
			var standUnit = $.trim(consoleDlg.find("#standUnit").val());
			var scale = $.trim(consoleDlg.find("#scale").val());
			if (scale=="") scale="0";		
			var maxRange = $.trim(consoleDlg.find("#maxRange").val());
			if (maxRange=="") maxRange="0";
			var minRange = $.trim(consoleDlg.find("#minRange").val());
			if (minRange=="") minRange="0";
			var factor = $.trim(consoleDlg.find("#factor").val());
			if (factor=="") factor="1";
			var alarmID = $.trim(consoleDlg.find("#alarm").val());
			var remark = $.trim(consoleDlg.find("#remark").val());
			
			var params = {
					"siteID" : siteID,
					"itemID" : itemID,					
					"eMaxValue" : eMaxValue,
					"eMinValue" : eMinValue,
					"overMaxValue" : overMaxValue,
					"overMinValue" : overMinValue,
					"standUnit" : standUnit,
					"scale" : scale,
					"maxRange" : maxRange,
					"minRange" : minRange,
					"factor" : factor,
					"alarmID" : alarmID,
					"remark" : remark
			};

			var actionUrl = getContextPath()+"/site/item/addSiteItem.do";

			$.ajax( {
					type: "POST",
					url : actionUrl,
					data : params,
					dataType : "json",
					cache : false,
					error : function(textStatus, errorThrown) {
						alert("系统ajax交互错误: " + textStatus);
					},
					success : function(data, textStatus) {
						if (data != null) {
							var dataRow = {
									id : data.id,
									"item.id" : data.item.id,
									"item.name" : data.item.name,
									eMaxValue : data.eMaxValue,
									eMinValue : data.eMinValue,
									overMaxValue : data.overMaxValue,
									overMinValue : data.overMinValue,
									standUnit : data.standUnit,
									maxRange : data.maxRange,
									minRange : data.minRange,
							   		factor : data.factor,
							   		"alarm.alarmName" : data.alarm.alarmName	
							};

							var srcrowid = $("#gridTable").jqGrid("getGridParam",
									"selrow");

							if (srcrowid) {
								$("#gridTable").jqGrid("addRowData",
										data.id, dataRow, "before",
										srcrowid);

							} else {
								$("#gridTable").jqGrid("addRowData",
										data.id, dataRow, "first");
							}
							consoleDlg.dialog("close");

							alert("站点监测项目添加操作成功!");

						} else {
							alert("[监测项目]重复，添加操作失败!");
						}
					}
				});  
		};
		
		var updateInfo = function() {
			var consoleDlg = $("#consoleDlg");

			if (checkValid()==false) return false;
			
			var id = $.trim(consoleDlg.find("#selectId").val());  
			var siteID = $.trim($("#gridContent").find("#sites").val());
			var itemID = $.trim(consoleDlg.find("#item").val());
			var eMaxValue = $.trim(consoleDlg.find("#eMaxValue").val());
			if (eMaxValue=="") eMaxValue = "0";
			var eMinValue = $.trim(consoleDlg.find("#eMinValue").val());			
			if (eMinValue=="") eMinValue = "0";
			var overMaxValue = $.trim(consoleDlg.find("#overMaxValue").val());
			if (overMaxValue=="") overMaxValue = "0";
			var overMinValue = $.trim(consoleDlg.find("#overMinValue").val());
			if (overMinValue=="") overMinValue="0";			
			var standUnit = $.trim(consoleDlg.find("#standUnit").val());
			var scale = $.trim(consoleDlg.find("#scale").val());
			if (scale=="") scale="0";		
			var maxRange = $.trim(consoleDlg.find("#maxRange").val());
			if (maxRange=="") maxRange="0";
			var minRange = $.trim(consoleDlg.find("#minRange").val());
			if (minRange=="") minRange="0";
			var factor = $.trim(consoleDlg.find("#factor").val());
			if (factor=="") factor="0";
			var alarmID = $.trim(consoleDlg.find("#alarm").val());
			var remark = $.trim(consoleDlg.find("#remark").val());
			
			var params = {
					"id" : id,
					"siteID" : siteID,
					"itemID" : itemID,					
					"eMaxValue" : eMaxValue,
					"eMinValue" : eMinValue,
					"overMaxValue" : overMaxValue,
					"overMinValue" : overMinValue,
					"standUnit" : standUnit,
					"scale" : scale,
					"maxRange" : maxRange,
					"minRange" : minRange,
					"factor" : factor,
					"alarmID" : alarmID,
					"remark" : remark
			};

			var actionUrl = getContextPath()+"/site/item/updateSiteItem.do";

			$.ajax( {
				type : "POST",
				url : actionUrl,
				data : params,
				dataType : "json",
				cache : false,
				error : function(textStatus, errorThrown) {
					alert("系统ajax交互错误: " + textStatus);
				},
				success : function(data, textStatus) {
					if (data != null) {
						var dataRow = {
								id : data.id,
								"item.id" : data.item.id,
								"item.name" : data.item.name,
								eMaxValue : data.eMaxValue,
								eMinValue : data.eMinValue,
								overMaxValue : data.overMaxValue,
								overMinValue : data.overMinValue,
								standUnit : data.standUnit,
								maxRange : data.maxRange,
								minRange : data.minRange,
						   		factor : data.factor,
						   		"alarm.alarmName" : data.alarm.alarmName
						};
						alert("站点监测项目更新成功!");
						consoleDlg.dialog("close");
						$("#gridTable").jqGrid("setRowData", data.id, dataRow);
					} else {
						alert("[监测项目]重复，修改操作失败!");
					}
				}
			});
		};
		
		var deleteInfo = function() {
			var consoleDlg = $("#consoleDlg");  
			
			var r=confirm("确认要删除该信息吗？");
			if (r==false) {
				consoleDlg.dialog("close"); 
				return false;
			}
	        
			var pId = $.trim(consoleDlg.find("#selectId").val()); 
	        var params = {"eID" : pId};  
	        var actionUrl = getContextPath() + "/site/item/deleteSiteItem.do";
	        $.ajax({  
	        	type : "POST",
	            url : actionUrl,  
	            data : params,  
	            //dataType : "json",  
	            cache : false,  
	            error : function(textStatus, errorThrown) {  
	                alert("系统ajax交互错误: " + textStatus);  
	            },  
	            success : function(data, textStatus) {  
	                if (data == "success") {  
	                    $("#gridTable").jqGrid("delRowData", pId);  
	                    consoleDlg.dialog("close");  
	                    alert("站点监测项目删除成功!");  
	                } else {  
	                    alert("删除操作失败!");  
	                }  
	            }  
	        });  
		};